package com.robot.mannge.common.config.security.handler;

import com.alibaba.fastjson2.JSON;
import com.robot.mannge.common.result.BaseResult;
import com.robot.mannge.common.result.ResultCode;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @Author: Smile
 * @Date: 2024/01/30/12:29
 * @Description:
 */

/**
 * 认证用户访问无权限资源处理器
 */
@Component
public class CustomerAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request,
                       HttpServletResponse response,
                       AccessDeniedException accessDeniedException) throws IOException, ServletException {
        //设置响应的编码格式
        response.setContentType("application/json;charset=utf-8");
        //转换json
        String jsonString = JSON.toJSONString(BaseResult.failed(ResultCode.NO_PRO, ResultCode.NO_PRO.message()));
        //输出到流
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(jsonString.getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}
